'use client'

import React, { useRef, useEffect } from 'react'
import { Card, Typography, Slider, Button, Space, Divider } from 'antd'
import {
    ZoomInOutlined,
    ZoomOutOutlined,
    RotateLeftOutlined,
    RotateRightOutlined,
    SettingOutlined,
    FullscreenOutlined
} from '@ant-design/icons'
import { useImageStore } from '@/stores/imageStore'
import { useUIStore } from '@/stores/uiStore'

const { Text } = Typography

// 2D面板组件
interface Panel2DProps {
    title: string
    imageData: unknown
    isMain?: boolean
}

const Panel2D: React.FC<Panel2DProps> = ({ title, imageData, isMain = false }) => {
    const canvasRef = useRef<HTMLCanvasElement>(null)

    useEffect(() => {
        if (canvasRef.current && imageData) {
            const canvas = canvasRef.current
            const ctx = canvas.getContext('2d')
            if (ctx) {
                // 响应式画布尺寸
                const rect = canvas.getBoundingClientRect()
                const width = rect.width || (isMain ? 600 : 400)
                const height = rect.height || (isMain ? 450 : 300)

                // 设置画布实际尺寸
                canvas.width = width
                canvas.height = height

                // 占位显示：绘制简单的网格和文字
                ctx.fillStyle = '#f0f0f0'
                ctx.fillRect(0, 0, width, height)

                // 绘制网格线 - 响应式网格大小
                ctx.strokeStyle = '#ddd'
                ctx.lineWidth = 1
                const gridSize = Math.min(width, height) / (isMain ? 12 : 10)
                for (let i = 0; i < width; i += gridSize) {
                    ctx.beginPath()
                    ctx.moveTo(i, 0)
                    ctx.lineTo(i, height)
                    ctx.stroke()
                }
                for (let i = 0; i < height; i += gridSize) {
                    ctx.beginPath()
                    ctx.moveTo(0, i)
                    ctx.lineTo(width, i)
                    ctx.stroke()
                }

                // 绘制标题和提示 - 响应式字体大小
                ctx.fillStyle = '#333'
                const baseFontSize = Math.max(12, Math.min(width, height) / (isMain ? 25 : 20))
                ctx.font = `${baseFontSize}px Arial`
                ctx.textAlign = 'center'
                ctx.fillText(title, width / 2, height / 2 - baseFontSize)

                ctx.font = `${baseFontSize * 0.8}px Arial`
                ctx.fillText('等待后端数据', width / 2, height / 2 + baseFontSize * 0.2)

                if (isMain && width > 400) {
                    ctx.font = `${baseFontSize * 0.7}px Arial`
                    ctx.fillText('主显示窗口 - 支持缩放、平移、测量', width / 2, height / 2 + baseFontSize * 1.2)
                }
            }
        }
    }, [imageData, title, isMain])

    return (
        <div className="panel-2d h-full flex flex-col">
            <div className="panel-header bg-gray-100 px-3 py-2 text-sm font-medium border-b flex items-center justify-between">
                <span>{title}</span>
                {isMain && (
                    <Button
                        type="text"
                        icon={<FullscreenOutlined />}
                        size="small"
                    />
                )}
            </div>
            <div className="panel-content flex-1 flex items-center justify-center bg-black">
                <canvas
                    ref={canvasRef}
                    className="border cursor-crosshair w-full h-full max-w-full max-h-full"
                />
            </div>
        </div>
    )
}

export const Viewer2D: React.FC = () => {
    const { currentImageData } = useImageStore()
    const { panelStates, updatePanelState } = useUIStore()

    const handleZoomChange = (value: number) => {
        updatePanelState('main', { zoom: value })
    }

    const handleWindowLevelChange = (value: number[]) => {
        updatePanelState('main', { windowLevel: [value[0], value[1]] })
    }

    return (
        <div className="viewer-2d h-full flex flex-col lg:flex-row slide-in-left">
            {/* 主显示区域 */}
            <div className="main-area flex-1 flex flex-col p-2">
                <Card
                    className="viewer-panel h-full"
                    bodyStyle={{ padding: 0, height: '100%' }}
                >
                    <Panel2D
                        title="主显示窗口"
                        imageData={currentImageData}
                        isMain={true}
                    />
                </Card>
            </div>

            {/* 侧边面板区域 - 响应式布局 */}
            <div className="side-area w-full lg:w-80 flex flex-row lg:flex-col p-2 lg:pl-0 space-x-2 lg:space-x-0 lg:space-y-2">
                {/* 辅助显示窗口 */}
                <Card
                    className="viewer-panel flex-1 lg:flex-1"
                    bodyStyle={{ padding: 0, height: '100%' }}
                >
                    <Panel2D
                        title="辅助窗口"
                        imageData={currentImageData}
                    />
                </Card>

                {/* 控制面板 */}
                <Card
                    title="控制面板"
                    className="viewer-panel flex-1 lg:flex-none"
                    bodyStyle={{ padding: '12px lg:16px' }}
                    style={{ height: '200px', minHeight: '200px' }}
                >
                    <div className="space-y-3 lg:space-y-4 h-full overflow-y-auto">
                        {/* 缩放控制 */}
                        <div>
                            <div className="flex items-center justify-between mb-1 lg:mb-2">
                                <Text strong className="text-sm lg:text-base">缩放</Text>
                                <Text type="secondary" className="text-xs">
                                    {(panelStates.main.zoom * 100).toFixed(0)}%
                                </Text>
                            </div>
                            <div className="flex items-center space-x-2">
                                <Button
                                    type="text"
                                    icon={<ZoomOutOutlined />}
                                    size="small"
                                    onClick={() => handleZoomChange(Math.max(0.1, panelStates.main.zoom - 0.1))}
                                />
                                <Slider
                                    min={0.1}
                                    max={5}
                                    step={0.1}
                                    value={panelStates.main.zoom}
                                    onChange={handleZoomChange}
                                    className="flex-1"
                                />
                                <Button
                                    type="text"
                                    icon={<ZoomInOutlined />}
                                    size="small"
                                    onClick={() => handleZoomChange(Math.min(5, panelStates.main.zoom + 0.1))}
                                />
                            </div>
                        </div>

                        {/* 移动端简化版控制 */}
                        <div className="lg:hidden">
                            <Text strong className="block mb-2 text-sm">快速操作</Text>
                            <Space wrap size="small">
                                <Button type="text" icon={<RotateLeftOutlined />} size="small">左转</Button>
                                <Button type="text" icon={<RotateRightOutlined />} size="small">右转</Button>
                                <Button type="text" icon={<SettingOutlined />} size="small">设置</Button>
                            </Space>
                        </div>

                        {/* 桌面端完整控制 */}
                        <div className="hidden lg:block space-y-4">
                            <Divider className="my-3" />

                            {/* 窗宽窗位控制 */}
                            <div>
                                <Text strong className="block mb-2">窗宽窗位</Text>
                                <div className="space-y-2">
                                    <div>
                                        <Text className="text-xs text-gray-600">窗宽: {panelStates.main.windowLevel[1]}</Text>
                                        <Slider
                                            min={1}
                                            max={4000}
                                            value={panelStates.main.windowLevel[1]}
                                            onChange={(value) => handleWindowLevelChange([panelStates.main.windowLevel[0], value])}
                                        />
                                    </div>
                                    <div>
                                        <Text className="text-xs text-gray-600">窗位: {panelStates.main.windowLevel[0]}</Text>
                                        <Slider
                                            min={-1000}
                                            max={3000}
                                            value={panelStates.main.windowLevel[0]}
                                            onChange={(value) => handleWindowLevelChange([value, panelStates.main.windowLevel[1]])}
                                        />
                                    </div>
                                </div>
                            </div>

                            <Divider className="my-3" />

                            {/* 图像操作 */}
                            <div>
                                <Text strong className="block mb-2">图像操作</Text>
                                <Space wrap>
                                    <Button
                                        type="text"
                                        icon={<RotateLeftOutlined />}
                                        size="small"
                                    >
                                        左转
                                    </Button>
                                    <Button
                                        type="text"
                                        icon={<RotateRightOutlined />}
                                        size="small"
                                    >
                                        右转
                                    </Button>
                                </Space>
                            </div>

                            <Divider className="my-3" />

                            {/* 测量工具 */}
                            <div>
                                <Text strong className="block mb-2">测量工具</Text>
                                <Space direction="vertical" size="small" className="w-full">
                                    <Button size="small" block>距离测量</Button>
                                    <Button size="small" block>角度测量</Button>
                                    <Button size="small" block>面积测量</Button>
                                </Space>
                            </div>

                            <Divider className="my-3" />

                            {/* 标注工具 */}
                            <div>
                                <Text strong className="block mb-2">标注工具</Text>
                                <Space direction="vertical" size="small" className="w-full">
                                    <Button size="small" block>文字标注</Button>
                                    <Button size="small" block>箭头标注</Button>
                                    <Button size="small" block>区域标注</Button>
                                </Space>
                            </div>
                        </div>
                    </div>
                </Card>
            </div>
        </div>
    )
}

export default Viewer2D